﻿#pragma warning disable CS8632
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.IO;

namespace Unity.Logger.Providers
{
    [ProviderAlias("StreamLogger")]
    public class StreamLoggerProvider : ILoggerProvider
    {
        internal const string DefaultOptionName = "StreamLogger.Default";

        AsyncStreamLineMessageWriter streamWriter;

        public StreamLoggerProvider(Stream stream, IOptionsMonitor<LogOptions> options)
            : this(stream, DefaultOptionName, options)
        {
        }

        public StreamLoggerProvider(Stream stream, string? optionName, IOptionsMonitor<LogOptions> options)
        {
            this.streamWriter = new AsyncStreamLineMessageWriter(stream, options.Get(optionName ?? DefaultOptionName));
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new AsyncProcessLog(categoryName, this.streamWriter);
        }

        public void Dispose()
        {
            this.streamWriter.DisposeAsync().AsTask().Wait();
        }
    }
}
